/**
 * 管理后台中心首页.
 * @type {Vue}
 */
let vmManageRecordsDns = new Vue({
    el: '#manage-records-dns',
    data () {
        let validateData = (rule, value, callback) => {
            if ('A' === this.form.type) {
                if (!QiStringUtils.isIpv4(value)) {
                    callback(new Error('A记录值必须为一个正确的IPV4地址'));
                }
            } else if ('AAAA' === this.form.type) {
                if (!QiStringUtils.isIpv6(value)) {
                    callback(new Error('AAAA记录值必须为一个正确的IPV6地址'));
                }
            } else if ('CNAME' === this.form.type || 'MX' === this.form.type) {
                if (!QiStringUtils.isDomain(value)) {
                    callback(new Error('CNAME或MX记录值必须为一个正确的域名'));
                }
            } else if ('SRV' === this.form.type) {
                if (!QiStringUtils.isSRV(value)) {
                    callback(new Error('SRV记录值不正确'));
                }
            }
            callback();
        };

        return {
            typeList: [
                'A',
                'MX',
                'CNAME',
                'NS',
                'PTR',
                'TXT',
                'AAAA',
                'SRV'
            ],
            netList: [],
            //列表所需数据
            formQuery: {
                domain: '',
                username: ''
            },
            listLoading: false,
            tableData : [],
            page: {
                current: 1,
                total: 0,
                page:1,
                pageSize:20
            },
            selectRows: [],

            //新增|修改
            isNew: false,
            dialogFormVisible: false,
            form: {
                origin: '',
                name: '',
                type: '',
                aux: 10,
                ttl: 600,
                netid: '0',
                data: ''
            },
            tmpForm: {
                origin: '',
                name: '',
                type: '',
                aux: 10,
                ttl: 600,
                netid: '0',
                data: ''
            },
            rules: {
                origin: [
                    { required: true, message: '请输入域名', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请选择解析类型', trigger: 'blur' }
                ],
                aux: [
                    { required: true, message: '请选择解析优先级', trigger: 'blur' }
                ],
                ttl: [
                    { required: true, message: '请选择TTL', trigger: 'blur' }
                ],
                netid: [
                    { required: true, message: '请选择网络组', trigger: 'blur' }
                ],
                data: [
                    { required: true, message: '请输入解析值', trigger: 'blur' },
                    { validator: validateData, trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        loadPage () {
            let domain = QiServletUtils.get("domain");
            if (!QiStringUtils.isBlank(domain)) {
                this.formQuery.domain = domain;
                this.tmpForm.origin = domain;
            }

            let url = '/api/manage/nets/action/collect' + (iFrameToken ? iFrameToken : ('?iframe-token=' + iFrameToken));
            QiRestClient.get(url, (data) => {
                let def = {id: '0', netname: '默认'};
                data.unshift(def)
                this.netList = data;
            }, (data) => {
                this.$message.error(data.message);
            });

            this.loadData();
        },
        /**
         * 架载统计数据.
         */
        loadData () {
            this.listLoading = true;
            let url = '/api/manage/records?';
            let param = $.extend({}, this.formQuery, {page: this.page.page, size: this.page.pageSize});
            url += QiServletUtils.mapToQueryString(param);
            url += (iFrameToken ? iFrameToken : ('&iframe-token=' + iFrameToken));
            QiRestClient.get(url, (data) => {
                this.tableData = data.items;
                this.page.total = data.total;
                this.listLoading = false;
            }, (data) => {
                this.$message.error(data.message);
                this.listLoading = false;
            });
        },
        /**
         * 查询触发.
         */
        onQuery () {
            this.page.current = 1;
            this.page.page = 1;
            this.loadData();
        },
        /**
         * 分页触发事件.
         * @param val
         */
        handleCurrentChange (val) {
            this.page.page = val;
            console.log("当前页数："+val);
            this.loadData();
        },
        /**
         * 选择事件.
         */
        handleSelectionChange (val) {
            this.selectRows = val;
        },
        /**
         * 新增.
         */
        showAdd () {
            this.isNew = true;
            this.form = Object.assign({}, this.tmpForm);
            this.dialogFormVisible = true;
        },
        /**
         * 标注.
         * @param row
         */
        showEdit (row) {
            this.isNew = false;
            this.form = Object.assign({}, row);
            this.form.origin = this.form.origin.substr(0, this.form.origin.length - 1);

            this.dialogFormVisible = true;
        },
        /**
         * 保存数据操作.
         */
        saveEdit () {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    let success =  (data) => {
                        this.$message.success('操作成功');
                        this.dialogFormVisible = false;
                        this.loadData();
                    };
                    let error = (data) => {
                        this.$message.error(data.message);
                    };

                    if (this.isNew) {
                        QiRestClient.post('/api/manage/records' + (iFrameToken ? iFrameToken : ('?iframe-token=' + iFrameToken)), this.form, success, error);
                    } else {
                        QiRestClient.put('/api/manage/records/' + this.form.id + (iFrameToken ? iFrameToken : ('?iframe-token=' + iFrameToken)), this.form, success, error);
                    }
                }
            });
        },
        /**
         * 详情.
         * @param row
         */
        goToSee (row) {
            let url = '?menu=2-2-1&domain=' + row.origin.substring(0, row.origin.length - 1) + '&recordId=' + row.id;
            let iframeToken = QiServletUtils.get('iframe-token');
            if (!QiStringUtils.isBlank(iframeToken)) {
                url += "&iframe-token=" + iframeToken;
            }
            location.href = url;
        },
        /**
         * 删除选中域名.
         */
        deleteAll () {
            if (this.selectRows.length < 1) {
                this.$message.error('请选择需要删除的解析记录.');
                return;
            }
            this.$confirm('确定需要移除选中解析记录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then( () => {
                let domains = [];
                this.selectRows.forEach((row) => {
                    domains.push(row.id);
                });
                QiRestClient.post('/api/manage/records/actions/delete' + (iFrameToken ? iFrameToken : ('?iframe-token=' + iFrameToken)),  domains, () => {
                    this.$message.success('操作成功');
                    this.loadData();
                },  (data) => {
                    this.$message.error(data.message);
                })
            });
        },
        /**
         * 删除.
         * @param row
         */
        deleteMessage (row) {
            let self = this;
            this.$confirm('确定需要移除选中记录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then( () => {
                QiRestClient.delete('/api/manage/records/' + row.id + (iFrameToken ? iFrameToken : ('?iframe-token=' + iFrameToken)),  () => {
                    self.$message.success('操作成功');
                    self.loadData();
                },  (data) => {
                    self.$message.error(data.message);
                })
            });
        }
    },
    mounted () {
        this.loadPage();
    }
});